import { toRefs, ref } from "vue"
import { useMapStore } from "../../store/useMap.js"
const { mapState } = toRefs(useMapStore())
import Query from "../../../zondy/lib/Query.js"
export const useGetRoad = () => {
  const hideRoadEle = ref(false)
  const roadlayer = ref(null)
  const roadsource = ref(null)
  roadsource.value = new ol.source.Vector({ wrapX: false })
  roadlayer.value = new ol.layer.Vector({
    source: roadsource.value,
  })
  const roadService = { name: "traffic", layerId: 1 }
  const freeStyle = new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: "#67C23A",
      width: 7,
    }),
  })
  const slowStyle = new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: "#409EFF",
      width: 7,
    }),
  })
  const congestionStyle = new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: "#F56C6C",
      width: 7,
    }),
  })
  let popup = null

  function getTimeRoad() {
    hideRoadEle.value = true
    if (popup) {
      return
    }
    popup = new ol.Overlay({
      //要转换成overlay的HTML元素
      element: document.querySelector("#popup"),
      //当前窗口可见
      autoPan: true,
      //Popup放置的位置
      positioning: "bottom-center",
      //是否应该停止事件传播到地图窗口
      stopEvent: true,
      autoPanAnimation: {
        //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
        duration: 250,
      },
    })
    mapState.value.map.addOverlay(popup)
    const position = [114.34166908892804, 30.498596188263036]
    popup.setPosition(position)
    Query.queryByLayer({ service: roadService, success: roadSuccess })
    mapState.value.map.addLayer(roadlayer.value)
  }
  function roadSuccess(e) {
    var format = new Zondy.Format.PolygonJSON()
    //将MapGIS要素JSON反序列化为ol.Feature类型数组
    var features = format.read(e)
    // console.log(features[0].values_.values_.车流量)
    const freeRoad = []
    const slowRoad = []
    const congestionRoad = []
    features.forEach(item => {
      if (item.values_.values_.车流量 <= 1000) {
        item.setStyle(freeStyle)
        freeRoad.push(item)
      } else if (item.values_.values_.车流量 < 1500) {
        item.setStyle(slowStyle)
        slowRoad.push(item)
      } else {
        item.setStyle(congestionStyle)
        congestionRoad.push(item)
      }
    })
    if (features) {
      roadsource.value.addFeatures(freeRoad)
      roadsource.value.addFeatures(slowRoad)
      roadsource.value.addFeatures(congestionRoad)
    }
  }
  function removeTimeRoad() {
    if (popup == null) {
      return
    }
    mapState.value.map.removeLayer(roadlayer.value)
    // roadsource.clear()
    // roadlayer.setVisible(false)
    popup.setPosition(undefined)
    popup = null
  }
  return { getTimeRoad, removeTimeRoad, hideRoadEle }
}
